<?php
namespace App\DBs\Stock;

use Illuminate\Support\Facades\DB;

class BoardDB extends BaseDB
{
    /**
     * 创板
     */

    protected $table = 'stock_board'; //创板
    protected $tStock = 'stock'; //库
    protected $tSource = 'stock_source'; //素材
    protected $tPlus = 'stock_plus'; //创单

    /**
     * 创板字段
     * uid 用户UID
     * uname 用户名
     * vid 库视频ID
     * plus 创作ID
     * isRender 1未申请，2申请中，3已渲染，
     */

    /**
     * 创板素材字段
     * uid 用户UID
     * vid 库视频ID
     * plus 创作ID
     * bid 创板ID
     * serial 编号顺序
     * link 素材地址或文字
     */

    public function __construct()
    {
    }

    /**
     * 后台列表
     */
    public function getAdminIndex($page, $size, $vid, $uid)
    {
        $pageStart = $page * $size;
        $query = DB::table($this->table)
            ->orderBy('id','desc');
        if ($vid) { $query = $query->where('vid',$vid); }
        if ($uid) { $query = $query->where('uid',$uid); }
        $queryTotal = $query->count();
        $models = $query->skip($pageStart)
            ->take($size)
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据');
        }
        $models = $this->jsonToArr($models);
        $dataArr = array();
        foreach ($models as $model) {
            $dataArr[] = [
                'boardId' => $model['id'],
                'uid' => $model['uid'],
                'uname' => $model['uname'],
                'vid' => $model['vid'],
                'boardName' => $model['caseName'],
                'vlink' => $model['vlink'],
                'del' => $model['del'],
            ];
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr, 'total'=>$queryTotal);
    }

    /**
     * 后台库视频
     */
    public function getAdminCases()
    {
        $vids = array();
        $dataArr = array();
        $models = DB::table($this->table)
            ->orderBy('id','asc')
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据', 'data'=>$dataArr);
        }
        $models = $this->jsonToArr($models);
        foreach ($models as $model) {
            if (!in_array($model['vid'],$vids)) {
                $resStocks = DB::table($this->tStock)
                    ->where('id',$model['vid'])
                    ->orderBy('id','desc')
                    ->skip(0)->take(1)
                    ->get();
                $stockOne = count($resStocks) ? $this->jsonToArr($resStocks[0]) : '';
                $stockTitle = $stockOne ? $stockOne['fileTitle'] : '';
                $dataArr[] = [
                    'videoId' => $model['vid'],
                    'videoTitle' => $stockTitle,
                ];
                $vids[] = $model['vid'];
            }
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr);
    }

    /**
     * 后台用户
     */
    public function getAdminUsers()
    {
        $uids = array();
        $dataArr = array();
        $models = DB::table($this->table)
            ->orderBy('id','asc')
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据', 'data'=>$dataArr);
        }
        $models = $this->jsonToArr($models);
        foreach ($models as $model) {
            if (!in_array($model['uid'],$uids)) {
                $resUser = $this->getUnameByUid($model['uid']);
                $dataArr[] = [
                    'uid' => $model['uid'],
                    'uname' => $resUser,
                ];
                $uids[] = $model['uid'];
            }
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr);
    }

    /**
     * APP列表
     */
    public function getAppIndex($page, $size, $uid, $bid)
    {
        $query = DB::table($this->table)->where('del',0)
            ->where('uid',$uid)->where('bid',$bid);
        $queryTotal = $query->count();
        $models = $query->orderBy('id','desc')
            ->skip($page)->take($size)
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据');
        }
        $models = $this->jsonToArr($models);
        $dataArr = array();
        foreach ($models as $model) {
            $dataArr[] = [
                'vid' => $model['vid'],
                'uname' => $model['uname'],
                'plus' => $model['plus'],
                'isRender' => $model['isRender'],
            ];
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr, 'total'=>$queryTotal);
    }

    /**
     * APP，通过UID、PID，获验证有没有
     */
    public function getExistByPlus($uid,$plusId)
    {
        //创单
        $pluss = DB::table($this->tPlus)->where('del',0)
            ->where('uid',$uid)->where('id',$plusId)
            ->skip(0)->take(1)
            ->get();
        $plusOne = count($pluss) ? $this->jsonToArr($pluss[0]) : '';
        $vid = $plusOne ? $plusOne['vid'] : 0;
        //库
        $stocks = DB::table($this->tStock)->where('del',0)
            ->where('id',$vid)->orderBy('id','desc')
            ->skip(0)->take(1)
            ->get();
        $stockOne = count($stocks) ? $this->jsonToArr($stocks[0]) : '';
        //创板
        $boards = DB::table($this->tBoard)->where('del',0)
            ->where('uid',$uid)->where('plus',$plusId)
            ->where('isRender',1)
            ->orderBy('id','desc')
            ->skip(0)->take(1)
            ->get();
        $boardOne = count($boards) ? $this->jsonToArr($boards[0]) : '';
        $bid = $boardOne ? $boardOne['id'] : 0;
        //素材
        $sources = DB::table($this->tSource)->where('del',0)
            ->where('bid',$bid)
            ->orderBy('serial','asc')
            ->get();
        $sources = count($sources) ? $this->jsonToArr($sources) : array();
        $isExist = ($plusOne && $boardOne && $sources) ? 1 : 0;
        return array(
            'stockOne' => $stockOne,
            'plusOne' => $plusOne,
            'boardOne' => $boardOne,
            'sources' => $sources,
            'isExist' => $isExist,
        );
    }

    /**
     * 加入创作增加
     * @param $uid 用户ID
     * @param $vid 首页视频ID
     */
    public function setAppAdd($exists, $items)
    {
        if (!$items) {
            return array('code'=>'-1', 'msg'=>'参数错误');
        }
        $stockOne = $exists['stockOne'];
        $plusOne = $exists['plusOne'];
        $boardOne = $exists['boardOne'];
        $sources = $exists['sources'];
        $sourceNum = $stockOne ? $stockOne['plusNum'] : 0;
        $plusId = $plusOne ? $plusOne['id'] : 0;
        $items['boardNum'] = $sourceNum;
        $items['boardHtml'] = $stockOne ? $stockOne['boardHtml'] : '';
        //开启事务
        DB::beginTransaction();
        try {
            //更新创板
            if (!$boardOne) {
                $boardId = DB::table($this->table)->insertGetId($items);
            } else {
                $boardId = $boardOne['id'];
            }
            //更新素材
            $sourceIds = array();
            if (!count($sources) && $sourceNum) {
                for ($i=1;$i<=$sourceNum;$i++) {
                    $sourceArr = array(
                        'uid' => $items['uid'],
                        'vid' => $items['vid'],
                        'plus' => $plusId,
                        'bid' => $boardId,
                        'serial' => $i,
                        'created_at' => time(),
                    );
                    $sourceIds[] = DB::table($this->tSource)
                        ->insertGetId($sourceArr);
                }
            }
            $dataArr = array(
                'plusId' => $plusId,
                'boardId' => $boardId,
                'sourceIds' => $sourceIds,
            );
            //提交事务
            DB::commit();
            return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
        }
    }
}